package com.imot.config;

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.Socket;

/**
 * ClassName: SocketManager
 * Description:
 * date: 2023/11/22 14:46
 *
 * @author imot-jiah.wang
 */
@Component
public class SocketManager {
    @Value("${socket.hostname}")
    private String hostname;

    @Value("${socket.port}")
    private int port;

    private Socket socket;

    public synchronized Socket getSocket() throws IOException {
        if (socket == null || socket.isClosed()) {
            socket = new Socket(hostname, port);
        }
        return socket;
    }

    // Optional: Close the socket if you need to
    public synchronized void closeSocket() throws IOException {
        if (socket != null && !socket.isClosed()) {
            socket.close();
        }
    }

    public String getHostname() {
        return hostname;
    }

    public void setHostname(String hostname) {
        this.hostname = hostname;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }
}


